<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RoleRealm - 角色选择</title>
    <link rel="stylesheet" href="/css/style.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'PingFang SC', 'Inter', sans-serif; background: #f8fafc; min-height: 100vh; }
        .header { background: white; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); padding: 15px 0; position: sticky; top: 0; z-index: 100; }
        .header-content { max-width: 1200px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; padding: 0 20px; }
        .logo { color: #1e3a8a; font-size: 24px; font-weight: bold; cursor: pointer; }
        .search-container { flex: 1; max-width: 400px; margin: 0 20px; position: relative; }
        .search-input { width: 100%; padding: 10px 40px 10px 16px; border: 2px solid #e5e7eb; border-radius: 25px; font-size: 14px; transition: all 0.3s ease; }
        .search-input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
        .search-icon { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af; }
        .header-actions { display: flex; gap: 15px; }
        .header-btn { padding: 8px 16px; border: none; border-radius: 20px; background: #f8fafc; color: #1e3a8a; cursor: pointer; font-size: 14px; transition: all 0.3s ease; }
        .header-btn:hover { background: #e5e7eb; }
        .main-container { max-width: 1200px; margin: 0 auto; display: grid; grid-template-columns: 250px 1fr 300px; gap: 20px; padding: 20px; }
        .sidebar { background: white; border-radius: 15px; padding: 20px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05); height: fit-content; }
        .sidebar-title { font-size: 18px; font-weight: bold; color: #1e3a8a; margin-bottom: 15px; }
        .filter-group { margin-bottom: 20px; }
        .filter-label { font-size: 14px; font-weight: bold; color: #374151; margin-bottom: 8px; display: block; }
        .filter-tags { display: flex; flex-wrap: wrap; gap: 8px; }
        .filter-tag { padding: 6px 12px; border: 2px solid #e5e7eb; border-radius: 20px; background: white; color: #6b7280; font-size: 12px; cursor: pointer; transition: all 0.3s ease; }
        .filter-tag:hover { border-color: #3b82f6; color: #3b82f6; }
        .filter-tag.active { background: #3b82f6; color: white; border-color: #3b82f6; }
        .characters-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; }
        .character-card { background: white; border-radius: 15px; padding: 20px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05); transition: all 0.3s ease; cursor: pointer; }
        .character-card:hover { transform: translateY(-5px); box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); }
        .character-avatar { width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, #3b82f6, #1e3a8a); display: flex; align-items: center; justify-content: center; color: white; font-size: 32px; font-weight: bold; margin: 0 auto 15px; }
        .character-name { font-size: 18px; font-weight: bold; color: #1e3a8a; text-align: center; margin-bottom: 8px; }
        .character-description { font-size: 14px; color: #6b7280; text-align: center; margin-bottom: 15px; line-height: 1.5; min-height: 40px; }
        .character-tags { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; margin-bottom: 15px; }
        .character-tag { padding: 4px 8px; background: #f1f5f9; color: #475569; border-radius: 12px; font-size: 11px; }
        .character-actions { display: flex; gap: 8px; margin-bottom: 15px; }
        .favorite-btn { padding: 8px 12px; border: 2px solid #e5e7eb; border-radius: 8px; background: white; color: #6b7280; cursor: pointer; transition: all 0.3s ease; font-size: 12px; }
        .favorite-btn:hover { border-color: #ef4444; color: #ef4444; }
        .favorite-btn.favorited { background: #ef4444; color: white; border-color: #ef4444; }
        .start-chat-btn { flex: 1; padding: 10px; background: #f59e0b; color: white; border: none; border-radius: 10px; font-size: 14px; font-weight: bold; cursor: pointer; transition: all 0.3s ease; }
        .start-chat-btn:hover { background: #d97706; }
        .recommendations { background: linear-gradient(135deg, #fef3c7, #fde68a); border-radius: 15px; padding: 20px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05); height: fit-content; }
        .recommendations-title { font-size: 18px; font-weight: bold; color: #92400e; margin-bottom: 15px; }
        .recommendation-item { display: flex; align-items: center; padding: 10px; background: white; border-radius: 10px; margin-bottom: 10px; cursor: pointer; transition: all 0.3s ease; }
        .recommendation-item:hover { transform: translateX(5px); }
        .recommendation-avatar { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, #3b82f6, #1e3a8a); display: flex; align-items: center; justify-content: center; color: white; font-size: 16px; font-weight: bold; margin-right: 10px; }
        .recommendation-name { font-size: 14px; font-weight: bold; color: #1e3a8a; }
        @media (max-width: 1024px) { .main-container { grid-template-columns: 200px 1fr; } .recommendations { display: none; } }
        @media (max-width: 768px) { .main-container { grid-template-columns: 1fr; padding: 10px; } .header-content { flex-direction: column; gap: 15px; } .search-container { max-width: 100%; margin: 0; } .sidebar { order: 2; } }
    </style>
    <script src="/js/api.js"></script>
    <script src="/js/auth.js"></script>
</head>
<body>
    <header class="header">
        <div class="header-content">
            <div class="logo" onclick="location.href='/'">RoleRealm</div>
            <div class="search-container">
                <input type="text" class="search-input" id="searchInput" placeholder="搜索角色名称、类别、时代...">
                <span class="search-icon">🔍</span>
            </div>
            <div class="header-actions">
                <button class="header-btn" onclick="location.href='/favorites.html'">我的收藏</button>
                <button class="header-btn" onclick="location.href='/user-settings.html'">设置</button>
                <button class="header-btn" onclick="Auth.logout()">退出</button>
            </div>
        </div>
    </header>

    <div class="main-container">
        <aside class="sidebar">
            <h3 class="sidebar-title">角色筛选</h3>
            <div class="filter-group">
                <label class="filter-label">类型</label>
                <div class="filter-tags" id="filterCategory">
                    <span class="filter-tag" data-value="history">历史人物</span>
                    <span class="filter-tag" data-value="literature">文学角色</span>
                    <span class="filter-tag" data-value="virtual">虚拟角色</span>
                </div>
            </div>
            <div class="filter-group">
                <label class="filter-label">时代</label>
                <div class="filter-tags" id="filterEra">
                    <span class="filter-tag" data-value="ancient">古代</span>
                    <span class="filter-tag" data-value="medieval">中世纪</span>
                    <span class="filter-tag" data-value="modern">近代</span>
                    <span class="filter-tag" data-value="contemporary">现代</span>
                </div>
            </div>
            <div class="filter-group">
                <label class="filter-label">地区</label>
                <div class="filter-tags" id="filterRegion">
                    <span class="filter-tag" data-value="china">中国</span>
                    <span class="filter-tag" data-value="europe">欧洲</span>
                    <span class="filter-tag" data-value="america">美洲</span>
                    <span class="filter-tag" data-value="asia">亚洲</span>
                </div>
            </div>
            <div class="filter-group">
                <label class="filter-label">语言</label>
                <div class="filter-tags" id="filterLanguage">
                    <span class="filter-tag" data-value="chinese">中文</span>
                    <span class="filter-tag" data-value="english">英文</span>
                    <span class="filter-tag" data-value="multilingual">多语言</span>
                </div>
            </div>
        </aside>

        <main class="characters-grid" id="charactersGrid"></main>

        <aside class="recommendations">
            <h3 class="recommendations-title">推荐角色</h3>
            <div id="recommendations"></div>
        </aside>
    </div>

    <script>
      Auth.requireAuth();

      const state = { q: '', category: '', era: '', region: '', language: '', page: 1, size: 20 };
      const grid = document.getElementById('charactersGrid');
      const searchInput = document.getElementById('searchInput');
      let userFavorites = new Set(); // 存储用户收藏的角色ID

      function avatarFromName(name) { return name ? name[0] : '角'; }

      // 加载用户收藏列表
      async function loadUserFavorites() {
        try {
          const data = await UsersApi.favorites(1, 100);
          const list = data.list || data.records || data.items || [];
          userFavorites.clear();
          list.forEach(fav => {
            if (fav.characterId) {
              userFavorites.add(fav.characterId);
            }
          });
        } catch (err) {
          console.error('加载收藏列表失败:', err);
        }
      }

      // 切换收藏状态
      async function toggleFavorite(characterId, button) {
        try {
          if (userFavorites.has(characterId)) {
            // 取消收藏
            await UsersApi.removeFavorite(characterId);
            userFavorites.delete(characterId);
            button.classList.remove('favorited');
            button.textContent = '收藏';
          } else {
            // 添加收藏
            await UsersApi.addFavorite(characterId);
            userFavorites.add(characterId);
            button.classList.add('favorited');
            button.textContent = '已收藏';
          }
        } catch (err) {
          alert(err.message || '操作失败');
        }
      }

      function tagPills(character) {
        const tags = [];
        if (character.category) tags.push(character.category);
        if (character.era) tags.push(character.era);
        if (character.region) tags.push(character.region);
        if (character.language) tags.push(character.language);
        return tags.map(t => `<span class="character-tag">${t}</span>`).join('');
      }

      function mapFiltersToBackend(params) {
        const categoryMap = { history: '历史人物', literature: '文学角色', virtual: '虚拟角色' };
        const eraMap = { ancient: '古代', medieval: '中世纪', modern: '近代', contemporary: '现代' };
        const regionMap = { china: '中国', europe: '欧洲', america: '美洲', asia: '亚洲' };
        const languageMap = { chinese: 'zh', english: 'en', multilingual: 'multi' };
        const mapped = { ...params };
        if (mapped.category) mapped.category = categoryMap[mapped.category] || mapped.category;
        if (mapped.era) mapped.era = eraMap[mapped.era] || mapped.era;
        if (mapped.region) mapped.region = regionMap[mapped.region] || mapped.region;
        if (mapped.language) mapped.language = languageMap[mapped.language] || mapped.language;
        return mapped;
      }

      async function loadCharacters() {
        grid.innerHTML = '';
        let params = { page: state.page, size: state.size };
        if (state.q) params.name = state.q; // simple contains by name
        if (state.category) params.category = state.category;
        if (state.era) params.era = state.era;
        if (state.region) params.region = state.region;
        if (state.language) params.language = state.language;
        params = mapFiltersToBackend(params);
        const data = await CharactersApi.list(params);
        const list = data.list || data.records || data.items || [];
        list.forEach(c => {
          const card = document.createElement('div');
          card.className = 'character-card';
          const isFavorited = userFavorites.has(c.id);
          card.innerHTML = `
            <div class="character-avatar">${avatarFromName(c.name)}</div>
            <h3 class="character-name">${c.name}</h3>
            <p class="character-description">${(c.description || c.background || '').slice(0, 72)}</p>
            <div class="character-tags">${tagPills(c)}</div>
            <div class="character-actions">
              <button class="favorite-btn ${isFavorited ? 'favorited' : ''}" data-character-id="${c.id}">
                ${isFavorited ? '已收藏' : '收藏'}
              </button>
              <button class="start-chat-btn">开始对话</button>
            </div>
          `;
          // 收藏按钮事件
          card.querySelector('.favorite-btn').addEventListener('click', async (e) => {
            e.stopPropagation();
            await toggleFavorite(c.id, e.target);
          });
          
          // 开始对话按钮事件
          card.querySelector('.start-chat-btn').addEventListener('click', async (e) => {
            e.stopPropagation();
            try {
              const conv = await ConversationsApi.create({ characterId: c.id, title: c.name, skillType: undefined });
              const conversationId = conv.id || conv.conversationId;
              location.href = `/chat.html?conversationId=${conversationId}&characterId=${c.id}`;
            } catch (err) { alert(err.message || '创建会话失败'); }
          });
          grid.appendChild(card);
        });
      }

      function bindFilters(containerId, key) {
        const container = document.getElementById(containerId);
        container.addEventListener('click', (e) => {
          const tag = e.target.closest('.filter-tag');
          if (!tag) return;
          const active = container.querySelector('.filter-tag.active');
          if (active === tag) { tag.classList.remove('active'); state[key] = ''; }
          else { if (active) active.classList.remove('active'); tag.classList.add('active'); state[key] = tag.dataset.value; }
          loadCharacters().catch(console.error);
        });
      }

      searchInput.addEventListener('input', () => { state.q = searchInput.value.trim(); loadCharacters().catch(console.error); });

      bindFilters('filterCategory', 'category');
      bindFilters('filterEra', 'era');
      bindFilters('filterRegion', 'region');
      bindFilters('filterLanguage', 'language');

      (async function init() {
        try {
          // 先加载用户收藏，再加载角色列表
          await loadUserFavorites();
          await loadCharacters();
          
          const recWrap = document.getElementById('recommendations');
          const rec = await CharactersApi.recommendations().catch(() => ({ list: [] }));
          const recList = rec.list || [];
          recWrap.innerHTML = '';
          recList.slice(0, 5).forEach(c => {
            const el = document.createElement('div');
            el.className = 'recommendation-item';
            el.innerHTML = `<div class="recommendation-avatar">${avatarFromName(c.name)}</div><div><div class="recommendation-name">${c.name}</div><div class="recommendation-reason">为你推荐</div></div>`;
            el.addEventListener('click', async () => {
              try {
                const conv = await ConversationsApi.create({ characterId: c.id, title: c.name });
                const conversationId = conv.id || conv.conversationId;
                location.href = `/chat.html?conversationId=${conversationId}&characterId=${c.id}`;
              } catch (err) { alert(err.message || '创建会话失败'); }
            });
            recWrap.appendChild(el);
          });
        } catch (err) { alert(err.message || '加载角色失败'); }
      })();
    </script>
</body>
</html>


